package com.ocom.ugcapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ocom.common.constant.WxServiceUrl;
import com.ocom.common.entity.company.EntityCompanyConfig;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.entity.master.EntityWechatAppInfo;
import com.ocom.common.entity.pay.EntityAppConfig;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.companyrole.GetCompanyConfigRequest;
import com.ocom.common.request.ugcapi.GetComIdCodeVo;
import com.ocom.common.request.ugcapi.GetCompanyInfoVo;
import com.ocom.common.request.ugcapi.GetCompanyListVo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.company.GzhCodeOfComVo;
import com.ocom.common.vo.company.GzhComListVo;
import com.ocom.common.vo.ugcapi.GzhComVo;
import com.ocom.common.vo.ugcapi.GzhUserInfo;
import com.ocom.ugcapi.client.CompanyClientService;
import com.ocom.ugcapi.client.HumanClientService;
import com.ocom.ugcapi.client.PayConfigClientService;
import com.ocom.ugcapi.config.RsaConfig;
import com.ocom.ugcapi.util.RSAHelper;
import com.ocom.ugcapi.vo.ConfigVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2022/8/10
 **/
@Slf4j
@RestController
public class CompanyController {

	@Autowired
	PayConfigClientService payConfigClientService;

	@Autowired
	CompanyClientService companyClientService;

	@Autowired
	HumanClientService humanClientService;


	@PostMapping(WxServiceUrl.Url_getAppConfig)
	public Result getAppConfig(@RequestBody ConfigVo configVo){
		Long companyId = 0l;
		if(configVo.getComId()!=0l){
			companyId= configVo.getComId();
		}
		if(companyId==0l){
			if(CommonUtil.isNull(configVo.getToken())){
				return ResultUtil.error(ResultEnum.Err_3062);
			}
			GzhUserInfo user = null;
			try {
				Gson gson=new Gson();
				String userStr  = RSAHelper.decipher(configVo.getToken(), RsaConfig.privateKey);
				user = gson.fromJson(userStr,GzhUserInfo.class);
			} catch (Exception e) {
				log.info("Token解析异常 【{}】", e);
				return ResultUtil.error(ResultEnum.Err_3042);
			}
			companyId=user.getComId();
		}

		//获取单位信息

		Map<String ,Object> map= new HashMap<>();


		Result result = payConfigClientService.getConfig(companyId);
		Result result1 = companyClientService.getCompanyInfoById(companyId);

		JSONObject entityAppConfig = new JSONObject();
		entityAppConfig.put("subAccount",false);
		if (result.getData() != null) {
			entityAppConfig = JSON.parseObject(JSON.toJSONString(result.getData()));

			Result result2 = payConfigClientService.getSubAccountList(companyId.intValue());
			System.out.println(result2);
			if(result2.getData()!=null){
				JSONArray jsonArray =JSON.parseArray(JSON.toJSONString(result2.getData()));
				if(jsonArray.size()>0){
					entityAppConfig.put("subAccount",true);
				}
			}
		}


		Result result2 = companyClientService.getCompanyConfig(companyId,"");
		if(result2.getCode()==200){
			List<EntityCompanyConfig>  companyConfigList = JSON.parseArray(JSON.toJSONString(result2.getData()), EntityCompanyConfig.class);
			for (EntityCompanyConfig companyConfig:companyConfigList){
				if(companyConfig.getConfig().equals("1")){
					entityAppConfig.put(companyConfig.getTab(),1);
				}else if(companyConfig.getConfig().equals("0")){
					entityAppConfig.put(companyConfig.getTab(),0);
				}else if(companyConfig.getConfig().equals("true")){
					entityAppConfig.put(companyConfig.getTab(),true);
				}else if(companyConfig.getConfig().equals("false")){
					entityAppConfig.put(companyConfig.getTab(),false);
				}else{
					entityAppConfig.put(companyConfig.getTab(),companyConfig.getConfig());
				}
			}
		}
		map.put("config",entityAppConfig);
		map.put("company",result1.getData());
		return ResultUtil.success(map);

	}

	@PostMapping(WxServiceUrl.Url_getDepts)
	public Result getDeptId(@RequestBody ConfigVo configVo){
		return humanClientService.getDeptList(configVo.getComId(),null,1);
	}

	@PostMapping(WxServiceUrl.URL_gzhGetCompanyInfo)
	public Result gzhGetCompanyInfo(@RequestBody Map<String,Object> map){
		GetCompanyInfoVo getCompanyInfoVo = JSON.parseObject(JSON.toJSONString(map), GetCompanyInfoVo.class);
		GzhComVo gzhComVo=new GzhComVo();
		//后台appid  已修改 ，则返回新appid

		Result result = companyClientService.getAppInfoByName(getCompanyInfoVo.getAppName())     ;
		if(result.getCode()!=200){
			return result;
		}
		EntityWechatAppInfo entityWechatAppInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityWechatAppInfo.class);

		if(getCompanyInfoVo.getUserInfo().getStatus()==1){
			gzhComVo.setStatus(1);
			//获取公众号信息
			gzhComVo.setAppid(entityWechatAppInfo.getAppid());
			return ResultUtil.success(gzhComVo);
		}

		Result result2 = companyClientService.getCompanyInfoById(entityWechatAppInfo.getComId());
		gzhComVo.setComId(entityWechatAppInfo.getComId());
		if(result2.getCode()==200){
			EntityCompanyInfo entityCompanyInfo= JSON.parseObject(JSON.toJSONString(result2.getData()), EntityCompanyInfo.class);
			gzhComVo.setComName(entityCompanyInfo.getComName());
		}

		if(!CommonUtil.isNull(getCompanyInfoVo.getComIdCode())){
			String[] comIdCodeStr = getCompanyInfoVo.getComIdCode().split("%");
			Long comId = Long.valueOf(comIdCodeStr[0]);
			gzhComVo.setComId(comId);
			Result result1 = companyClientService.getGzhCodeOfCom(comId);
			GzhCodeOfComVo gzhCodeOfComVo = JSON.parseObject(JSON.toJSONString(result1.getData()), GzhCodeOfComVo.class);
			if(!gzhCodeOfComVo.getComIdCode().equals(getCompanyInfoVo.getComIdCode())){
				log.error("comIdCode异常 【{}】 ",getCompanyInfoVo);
				gzhComVo.setStatus(2);
				return ResultUtil.success(gzhComVo);
			}
			if(comId.compareTo(entityWechatAppInfo.getComId())!=0){
				log.error("单位Id不一致 【{}】 ",getCompanyInfoVo);
				gzhComVo.setStatus(2);
				return ResultUtil.success(gzhComVo);
			}
			Result result3= companyClientService.getCompanyInfoById(comId);
			if(result3.getCode()==200){
				EntityCompanyInfo entityCompanyInfo= JSON.parseObject(JSON.toJSONString(result3.getData()), EntityCompanyInfo.class);
				gzhComVo.setComName(entityCompanyInfo.getComName());
			}
		}
		return ResultUtil.success(gzhComVo);
	}


	@PostMapping(WxServiceUrl.URL_getCompanyList)
	public Result getCompanyList(@RequestBody Map<String,Object> map){
		GetCompanyListVo companyListVo = JSON.parseObject(JSON.toJSONString(map), GetCompanyListVo.class);

		GzhComVo gzhComVo=new GzhComVo();
		//后台appid  已修改 ，则返回新appid

		Result result = companyClientService.getAppInfoByName(companyListVo.getAppName())     ;
		if(result.getCode()!=200){
			return result;
		}
		EntityWechatAppInfo entityWechatAppInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityWechatAppInfo.class);

//		if(companyListVo.getUserInfo().getStatus()==1){
//			gzhComVo.setStatus(1);
//			//获取公众号信息
//			gzhComVo.setAppid(entityWechatAppInfo.getAppid());
//			return ResultUtil.success(gzhComVo);
//		}
		gzhComVo.setAppid(entityWechatAppInfo.getAppid());
		Result  result1  = companyClientService.getCompanyListByAgentGzh(entityWechatAppInfo.getAppid(),companyListVo.getBindRegister());

		if(result1.getCode()==200){
			List<GzhComListVo> list = JSON.parseArray(JSON.toJSONString(result1.getData()), GzhComListVo.class);
			gzhComVo.setComList(list);
		}

		return ResultUtil.success(gzhComVo);
	}

	@PostMapping(WxServiceUrl.URL_comIdCode)
	public Result comIdCode(@RequestBody Map<String,Object> map2){
		GetComIdCodeVo comIdCodeVo = JSON.parseObject(JSON.toJSONString(map2), GetComIdCodeVo.class);

		Result result = companyClientService.getAppInfoByName(comIdCodeVo.getAppName())     ;
		if(result.getCode()!=200){
			return result;
		}
		EntityWechatAppInfo entityWechatAppInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityWechatAppInfo.class);

		Map<String,Object>  objectMap =new HashMap<>();

		Result result1 = companyClientService.getGzhCodeOfCom(entityWechatAppInfo.getComId());
		GzhCodeOfComVo gzhCodeOfComVo = JSON.parseObject(JSON.toJSONString(result1.getData()), GzhCodeOfComVo.class);
		objectMap.put("comIdCode",gzhCodeOfComVo.getComIdCode());
		objectMap.put("url","");

		Result result2 = companyClientService.getAppFunc(comIdCodeVo.getUserInfo().getComId(),comIdCodeVo.getUserInfo().getAppId());



		if(result2.getCode()!=200){
			return ResultUtil.success(objectMap);
		}

		EntityAppConfig entityAppConfig = JSON.parseObject(JSON.toJSONString(result2.getData()), EntityAppConfig.class);

		/**
		 * 4、调用单位微服务接口3.16 urlBindRegister（参数：bind、register）获取pageUrl
		 * 如果pageUrl为空，bindUrl :=空
		 * 否则bindUrl := pageUrl + “?AppName=” + app_name + “&com_id_code=” + comIdCode
		 */

		if(comIdCodeVo.getBindRegister()==1){
			if(entityAppConfig.getBind()<=0){
				return ResultUtil.success(objectMap);
			}
			Result result3 =  companyClientService.urlBindRegister(1,0);
			if(result3.getCode()==200){
				Map<String, String> map = JSON.parseObject(JSON.toJSONString(result3.getData()), Map.class);
				//bindUrl := pageUrl + “?AppName=” + app_name + “&com_id_code=” + comIdCode
				objectMap.put("url",map.get("pageUrl")+
						"?appName="+comIdCodeVo.getAppName()+
						"&comIdCode="+gzhCodeOfComVo.getComIdCode());
			}
		}
		if(comIdCodeVo.getBindRegister()==2){
			if(entityAppConfig.getRegister()==0){
				return ResultUtil.success(objectMap);
			}
			Result result3 =  companyClientService.urlBindRegister(0,1);
			if(result3.getCode()==200){
				Map<String, String> map = JSON.parseObject(JSON.toJSONString(result3.getData()), Map.class);
				//bindUrl := pageUrl + “?AppName=” + app_name + “&com_id_code=” + comIdCode
				objectMap.put("url",map.get("pageUrl")+
						"?appName="+comIdCodeVo.getAppName()+
						"&comIdCode="+gzhCodeOfComVo.getComIdCode());
			}
		}
		return ResultUtil.success(objectMap);
	}


	@PostMapping(WxServiceUrl.URL_subAccount)
	public Result subAccount(@RequestBody Map<String, Object> map) {
		GzhUserInfo user = (GzhUserInfo) map.get("userInfo");
		return payConfigClientService.getSubAccountList(user.getComId().intValue());
	}


	@PostMapping(WxServiceUrl.URL_evaluateConfigOnShow)
	public Result companyConfigOnShow(@Validated @RequestBody GetCompanyConfigRequest request) {
		return companyClientService.getCompanyConfig(request.getComId(), request.getTab());
	}

}
